// 快捷键冲突检测组件
// 检测和显示快捷键冲突

import React, { useEffect, useState } from 'react';
import { AlertTriangle, X, Check } from 'lucide-react';

interface ShortcutConflict {
  shortcut: string;
  conflictingActions: Array<{
    id: string;
    name: string;
    description: string;
  }>;
}

interface ShortcutConflictDetectorProps {
  shortcuts: Record<string, string>;
  onConflictResolved?: (actionId: string, newShortcut: string) => void;
}

export const ShortcutConflictDetector: React.FC<ShortcutConflictDetectorProps> = ({
  shortcuts,
  onConflictResolved
}) => {
  const [conflicts, setConflicts] = useState<ShortcutConflict[]>([]);
  const [resolvingConflict, setResolvingConflict] = useState<string | null>(null);
  const [newShortcut, setNewShortcut] = useState('');
  const [isRecording, setIsRecording] = useState(false);

  // 检测冲突
  useEffect(() => {
    const detectedConflicts = detectConflicts(shortcuts);
    setConflicts(detectedConflicts);
  }, [shortcuts]);

  // 检测快捷键冲突
  const detectConflicts = (shortcuts: Record<string, string>): ShortcutConflict[] => {
    const shortcutMap: Record<string, string[]> = {};
    const conflicts: ShortcutConflict[] = [];

    // 构建快捷键映射
    Object.entries(shortcuts).forEach(([actionId, shortcut]) => {
      if (!shortcut) return;
      
      if (!shortcutMap[shortcut]) {
        shortcutMap[shortcut] = [];
      }
      shortcutMap[shortcut].push(actionId);
    });

    // 找出冲突
    Object.entries(shortcutMap).forEach(([shortcut, actionIds]) => {
      if (actionIds.length > 1) {
        conflicts.push({
          shortcut,
          conflictingActions: actionIds.map(id => ({
            id,
            name: getActionName(id),
            description: getActionDescription(id)
          }))
        });
      }
    });

    return conflicts;
  };

  // 获取操作名称
  const getActionName = (actionId: string): string => {
    const actionNames: Record<string, string> = {
      'editor.save': '保存文件',
      'editor.saveAll': '保存所有文件',
      'editor.newFile': '新建文件',
      'editor.openFile': '打开文件',
      'tab.close': '关闭标签页',
      'tab.next': '下一个标签页',
      'tab.previous': '上一个标签页',
      'edit.undo': '撤销',
      'edit.redo': '重做',
      'edit.copy': '复制',
      'edit.paste': '粘贴',
      'search.find': '查找',
      'search.replace': '替换'
    };
    return actionNames[actionId] || actionId;
  };

  // 获取操作描述
  const getActionDescription = (actionId: string): string => {
    const actionDescriptions: Record<string, string> = {
      'editor.save': '保存当前编辑的文件',
      'editor.saveAll': '保存所有打开的文件',
      'editor.newFile': '创建新的文件',
      'editor.openFile': '打开文件对话框',
      'tab.close': '关闭当前标签页',
      'tab.next': '切换到下一个标签页',
      'tab.previous': '切换到上一个标签页',
      'edit.undo': '撤销上一个操作',
      'edit.redo': '重做上一个撤销的操作',
      'edit.copy': '复制选中的内容',
      'edit.paste': '粘贴剪贴板内容',
      'search.find': '在当前文件中查找',
      'search.replace': '查找并替换'
    };
    return actionDescriptions[actionId] || '';
  };

  // 开始解决冲突
  const startResolving = (actionId: string) => {
    setResolvingConflict(actionId);
    setNewShortcut(shortcuts[actionId] || '');
    setIsRecording(false);
  };

  // 取消解决冲突
  const cancelResolving = () => {
    setResolvingConflict(null);
    setNewShortcut('');
    setIsRecording(false);
  };

  // 确认解决冲突
  const confirmResolving = () => {
    if (resolvingConflict && newShortcut) {
      onConflictResolved?.(resolvingConflict, newShortcut);
      cancelResolving();
    }
  };

  // 开始录制快捷键
  const startRecording = () => {
    setIsRecording(true);
    setNewShortcut('');
  };

  // 处理键盘事件
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (!isRecording) return;

    e.preventDefault();
    e.stopPropagation();

    const keys = [];
    if (e.ctrlKey) keys.push('Ctrl');
    if (e.shiftKey) keys.push('Shift');
    if (e.altKey) keys.push('Alt');
    if (e.metaKey) keys.push('Cmd');

    const key = e.key;
    if (key !== 'Control' && key !== 'Shift' && key !== 'Alt' && key !== 'Meta') {
      keys.push(key.length === 1 ? key.toUpperCase() : key);
      setNewShortcut(keys.join('+'));
      setIsRecording(false);
    }
  };

  if (conflicts.length === 0) {
    return (
      <div className="flex items-center space-x-2 text-green-600 dark:text-green-400">
        <Check className="w-4 h-4" />
        <span className="text-sm">没有检测到快捷键冲突</span>
      </div>
    );
  }

  return (
    <div className="space-y-4" onKeyDown={handleKeyDown} tabIndex={-1}>
      <div className="flex items-center space-x-2 text-orange-600 dark:text-orange-400">
        <AlertTriangle className="w-5 h-5" />
        <span className="font-medium">检测到 {conflicts.length} 个快捷键冲突</span>
      </div>

      {conflicts.map((conflict, index) => (
        <div key={index} className="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg p-4">
          <div className="flex items-center justify-between mb-3">
            <div>
              <span className="font-medium text-orange-800 dark:text-orange-200">
                快捷键冲突: 
              </span>
              <kbd className="ml-2 px-2 py-1 text-sm font-mono bg-orange-100 dark:bg-orange-800 rounded">
                {conflict.shortcut}
              </kbd>
            </div>
          </div>

          <div className="space-y-2">
            <p className="text-sm text-orange-700 dark:text-orange-300">
              以下操作使用了相同的快捷键：
            </p>
            
            {conflict.conflictingActions.map((action) => (
              <div key={action.id} className="flex items-center justify-between p-2 bg-white dark:bg-gray-800 rounded border">
                <div>
                  <div className="font-medium text-gray-900 dark:text-white">
                    {action.name}
                  </div>
                  <div className="text-sm text-gray-600 dark:text-gray-400">
                    {action.description}
                  </div>
                </div>
                
                {resolvingConflict === action.id ? (
                  <div className="flex items-center space-x-2">
                    <input
                      type="text"
                      value={newShortcut}
                      onChange={(e) => setNewShortcut(e.target.value)}
                      placeholder={isRecording ? "按下快捷键..." : "输入新快捷键"}
                      className="w-32 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                      readOnly={isRecording}
                    />
                    <button
                      onClick={startRecording}
                      className="px-2 py-1 text-xs bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded hover:bg-blue-200 dark:hover:bg-blue-800"
                    >
                      {isRecording ? '录制中...' : '录制'}
                    </button>
                    <button
                      onClick={confirmResolving}
                      className="p-1 text-green-600 hover:text-green-700 dark:text-green-400 dark:hover:text-green-300"
                      disabled={!newShortcut}
                    >
                      <Check className="w-4 h-4" />
                    </button>
                    <button
                      onClick={cancelResolving}
                      className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </div>
                ) : (
                  <button
                    onClick={() => startResolving(action.id)}
                    className="px-3 py-1 text-sm bg-orange-100 dark:bg-orange-800 text-orange-800 dark:text-orange-200 rounded hover:bg-orange-200 dark:hover:bg-orange-700"
                  >
                    修改快捷键
                  </button>
                )}
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};
